// Fill out your copyright notice in the Description page of Project Settings.

#include "Isalong2.h"
#include "Bag.h"
#include "CGameManager.h"

Bag::Bag(float bagSize)
{
	_bagSize = bagSize;
}

Bag::~Bag()
{
}

void Bag::PickUp(UObject* owner)
{
	_owner = owner;
}

bool Bag::PutIn(int id, int count)
{
	if (count*ItemType::GetWeightByID(id)+GetCurrentWeight()>_bagSize)
	{
		return false;
	}
	if (ItemType::GetIsAttachable(id))
	{
		while (count>0)
		{
			_data.Push(Item(id, 1));
			count--;
		}
		return true;
	}
	for (auto& i:_data)
	{
		if (i._itemID==id)
		{
			i._itemCount += count;
			return true;
		}
	}
	_data.Push(Item(id, count));
	return true;
}

FGuid Bag::PutIn_Guid(int id, int count)
{
	if (count*ItemType::GetWeightByID(id) + GetCurrentWeight() > _bagSize)
	{
		return FGuid();
	}
	if (ItemType::GetIsAttachable(id))
	{
		Item readyPutIn;
		while (count > 0)
		{
			readyPutIn = Item(id, 1);
			_data.Push(readyPutIn);
			count--;
		}
		return readyPutIn._guid;
	}
	for (auto& i : _data)
	{
		if (i._itemID == id)
		{
			i._itemCount += count;
			return i._guid;
		}
	}
	Item readIn = Item(id, count);
	_data.Push(readIn);
	return readIn._guid;
}

bool Bag::TakeOut(int id, int count)
{
	// check can take out
	int alreadyCount = 0;
	for (int i=0;i<_data.Num();i++)
	{
		if (_data[i]._itemID==id)
		{
			alreadyCount += _data[i]._itemCount;
		}
	}
	if (alreadyCount<count)
	{
		return false;
	}
	for (int i=0;i<_data.Num();i++)
	{
		if (count==0)
		{
			break;
		}
		if (_data[i]._itemID==id)
		{
			if (_data[i]._itemCount<=count)
			{
				count -= _data[i]._itemCount;
				_data.RemoveAt(i);
				i--;
			}
			else
			{
				_data[i]._itemCount -= count;
				count = 0;
			}
		}
	}
	return true;
}

bool Bag::TakeOut(FGuid guid, int count)
{
	for (int i=0;i<_data.Num();i++)
	{
		if (_data[i]._guid==guid&&_data[i]._itemCount>=count)
		{
			if (_data[i]._itemCount==count)
			{
				_data.RemoveAt(i);
			}
			else
			{
				_data[i]._itemCount -= count;
			}
			return true;
		}
	}
	return false;
}

// set all addition with the same item id
bool Bag::SetAddition(int id, int val)
{
	for (auto& i:_data)
	{
		if (i._itemID==id)
		{
			i._addition = val;
		}
	}
	return true;
}

bool Bag::SetAddition(FGuid guid, int val)
{
	for (auto& i : _data)
	{
		if (i._guid == guid)
		{
			i._addition = val;
			return true;
		}
	}
	return false;
}

TArray<Item> Bag::ReadData()
{
	TArray<Item> newArray;
	for (auto& i:_data)
	{
		newArray.Push(Item(i._itemID, i._itemCount, i._addition,i._guid));
	}
	return newArray;
}

UObject* Bag::GetOwner()
{
	return _owner;
}

float Bag::GetBagSize()
{
	return _bagSize;
}

float Bag::GetCurrentWeight()
{
	float weight = 0;
	for (auto& i:_data)
	{
		weight += i.GetWeight();
	}
	return weight;
}
